from django.shortcuts import render

# Create your views here.
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.generics import ListAPIView, GenericAPIView

from .models import SKU,GoodsCategory
from . import serializers
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response


class SKUSearchViewSet(HaystackViewSet):
    """SKU搜索"""

    # 指定索引模型类
    index_models = [SKU]
    # 指定序列化器
    serializer_class = serializers.SKUIndexSerializer


# url(r'^categories/(?P<category_id>\d+)/skus/', views.SKUListView.as_view()),
class SKUListView(ListAPIView):
    """
    商品列表，排序和分页
    """
    # 指定序列化器
    serializer_class = serializers.SKUSerializer

    # 指定排序后端
    filter_backends = [OrderingFilter]
    # 指定排序的字段，由ordering 接收
    ordering_fields = ('create_time', 'price', 'sales')

    # 指定查询集
    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        # 商品列表中的数据需要满足指定的分类和必须是上架的商品
        return SKU.objects.filter(category_id=category_id, is_launched=True)

# url(r'^categories/(?P<pk>\d+)/$', views.CategoryView.as_view()),
class CategoryView(GenericAPIView):
    """
    商品列表页面包屑导航
    """
    queryset = GoodsCategory.objects.all()

    def get(self, request, pk=None):
        ret = dict(
            cat1='',
            cat2='',
            cat3=''
        )
        category = self.get_object()
        if category.parent is None:
            # 当前类别为一级类别
            ret['cat1'] = serializers.ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodscategory_set.count() == 0:
            # 当前类别为三级
            ret['cat3'] = serializers.CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = serializers.CategorySerializer(cat2).data
            ret['cat1'] = serializers.ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前类别为二级
            ret['cat2'] = serializers.CategorySerializer(category).data
            ret['cat1'] = serializers.ChannelSerializer(category.parent.goodschannel_set.all()[0]).data

        return Response(ret)